<template>
  <div class="organize-tree-select">
    <el-popover
      v-model:visible="visible"
      placement="bottom-start"
      :width="300"
      trigger="manual"
      popper-class="organize-tree-popover"
    >
      <template #reference>
        <el-input
          v-model="displayText"
          placeholder="请选择部门"
          readonly
          :clearable="clearable"
          @clear="handleClear"
          @click.stop="handleInputClick"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click.stop="handleInputClick">
              <ArrowDown :class="{ 'is-reverse': visible }" />
            </el-icon>
          </template>
        </el-input>
      </template>
      
      <div class="tree-select-content">
        <div class="tree-container">
          <el-tree
            ref="treeRef"
            :data="organizeStore.organizeTree"
            :props="treeProps"
            node-key="id"
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <template #default="{ node }">
              <div class="tree-node">
                <span class="node-label">{{ node.label }}</span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElPopover, ElInput, ElTree, ElIcon } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { useOrganizeStore } from '@/stores/organize'
import type { OrganizeTreeNode } from '@/types'

// Props
interface Props {
  modelValue?: number
  placeholder?: string
  clearable?: boolean
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
  placeholder: '请选择部门',
  clearable: true,
  disabled: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: number | undefined]
  'change': [value: number | undefined, node: OrganizeTreeNode | null]
}>()

// 使用store
const organizeStore = useOrganizeStore()

// 响应式数据
const visible = ref(false)
const treeRef = ref<InstanceType<typeof ElTree>>()

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 计算属性
const displayText = computed(() => {
  if (!props.modelValue) return ''
  const node = organizeStore.findOrganizeById(props.modelValue)
  return node ? node.name : ''
})


// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  if (newVal && treeRef.value) {
    treeRef.value.setCurrentKey(newVal)
  }
})

// 监听visible变化
watch(visible, (newVal) => {
  if (newVal && organizeStore.organizeTree.length === 0) {
    organizeStore.fetchOrganizeTree()
  }
})

// 方法
const handleInputClick = () => {
  visible.value = !visible.value
}

const handleNodeClick = (data: OrganizeTreeNode) => {
  emit('update:modelValue', data.id)
  emit('change', data.id, data)
  visible.value = false
}

const handleClear = () => {
  emit('update:modelValue', undefined)
  emit('change', undefined, null)
}

// 组件挂载时加载数据
onMounted(() => {
  if (organizeStore.organizeTree.length === 0) {
    organizeStore.fetchOrganizeTree()
  }
})
</script>

<style scoped lang="scss">
.organize-tree-select {
  width: 100%;
}

.tree-select-content {
  max-height: 300px;
  
  .tree-container {
    max-height: 300px;
    overflow-y: auto;
  }
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  
  .node-label {
    font-size: 14px;
    color: #303133;
  }
}

:deep(.el-input__icon) {
  transition: transform 0.3s;
  
  &.is-reverse {
    transform: rotate(180deg);
  }
}

:deep(.el-tree-node__content) {
  height: 32px;
  padding: 0 8px;
  
  &:hover {
    background-color: #f5f7fa;
  }
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #e6f7ff;
  color: #1890ff;
}

:deep(.el-tree-node__expand-icon) {
  color: #c0c4cc;
  
  &.is-leaf {
    color: transparent;
  }
}
</style>

<style>
.organize-tree-popover {
  padding: 8px !important;
}
</style>
